package cn.nkjobsearch.others;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import cn.nkjobsearch.mysql.MysqlConn;
import cn.nkjobsearch.publicClass.NKJSMath;

/*
 * MIN * x^99 = MAX
 * */
public class MakeRankForKeyword {
	public void makeRank() {

		this.makeX();
		String sql = "SELECT `id`, `count` FROM KEYWORD WHERE `count` != 0 ORDER BY `count` ASC;";
		rs = mysql.executeQuery(sql);
		try {
			while (rs.next()) {
				int[] r = new int[2];
				r[0] = rs.getInt(1);
				/**
				 * 等级为 minRank - maxRank
				 * */
				r[1] = (int) (NKJSMath.log( max / (double)rs.getInt(2), x) * minRank);
				res.add(r);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		writeRankToDB(res);
		mysql.close();
	}

	/**
	 * 计算公式 MIN * x^levelNum = MAX 中的x
	 * */
	private void makeX() {
		String sql = "SELECT MIN(COUNT),MAX(COUNT) FROM KEYWORD WHERE COUNT != 0;";
		rs = mysql.executeQuery(sql);
		try {
			if (rs.next()) {
				min = rs.getInt(1);
				max = rs.getInt(2);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.x = Math.pow((double) max / (double) min,
				1.0 / (double) (levelNum - 1));
	}

	/**
	 * 讲等级Rank值数据库，并重置count=min的keyword的Rank为minRank（安装算法计算为0）
	 * */
	private void writeRankToDB(ArrayList<int[]> res) {
		for (int i = 0; i < res.size(); i++) {
			String sql = "UPDATE `KEYWORD` SET `RANK` = '"
				+ res.get(i)[1] + "' WHERE `ID` = " + res.get(i)[0];
			mysql.executeUpdate(sql);
		}
		mysql.executeUpdate("UPDATE `KEYWORD` SET `RANK` = '" + maxRank + "' WHERE `COUNT` = " + min);
	}

	private MysqlConn mysql = new MysqlConn();
	private ResultSet rs = null;
	private int min = 0;
	private int max = 0;
	private final int levelNum = 100;
	private double x;
	private ArrayList<int[]> res = new ArrayList<int[]>();
	private final int minRank = 10;
	private final int maxRank = 1000;
}
